<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useTokenStore } from '@/stores/token.js'
import request from '@/utils/request.js'

export default {
  name: 'UserInfo',
  setup() {
    const userInfo = ref({})
    const originalUsername = ref('')
    const isEditing = ref(false)
    const tokenStore = useTokenStore()
    const formRef = ref(null)

    const rules = ref({
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ]
    })

    const getUserInfo = async () => {
      try {
        const response = await request.get('/user/info')
        if (response.code === 1) {
          userInfo.value = response.data
          originalUsername.value = response.data.username
        } else {
          ElMessage.error(response.msg || '获取用户信息失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const saveChanges = async () => {
      try {
        const response = await request.put('/user', {
          id: userInfo.value.id,
          username: userInfo.value.username
        })
        if (response.code === 1) {
          ElMessage.success('保存成功')
          isEditing.value = false
        } else {
          ElMessage.error(response.msg || '保存失败')
        }
      } catch (error) {
        ElMessage.error('服务异常')
      }
    }

    const cancelChanges = () => {
      userInfo.value.username = originalUsername.value
      isEditing.value = false
    }

    const getRoleText = (role) => {
      return role === 1 ? '用户' : role === 2 ? '管理员' : '未知';
    }

    const getStatusText = (status) => {
      return status === 1 ? '正常' : status === 2 ? '冻结' : '未知';
    }

    const formattedCreateTime = computed(() => {
      return formatDate(userInfo.value.createTime)
    })

    const formattedUpdateTime = computed(() => {
      return formatDate(userInfo.value.updateTime)
    })

    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    }

    onMounted(() => {
      getUserInfo()
    })

    return {
      userInfo,
      isEditing,
      saveChanges,
      cancelChanges,
      formattedCreateTime,
      formattedUpdateTime,
      formRef,
      rules,
      getRoleText,
      getStatusText
    }
  }
}
</script>

<template>
  <div class="user-info-container">
    <h2>基本资料</h2>
    <el-form :model="userInfo" :rules="rules" ref="formRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userInfo.username" :disabled="!isEditing"></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-input :value="getRoleText(userInfo.role)" disabled></el-input>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-input :value="getStatusText(userInfo.status)" disabled></el-input>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-input v-model="formattedCreateTime" disabled></el-input>
      </el-form-item>
      <el-form-item label="最后更新时间" prop="updateTime">
        <el-input v-model="formattedUpdateTime" disabled></el-input>
      </el-form-item>
      <el-form-item v-if="isEditing" class="action-buttons">
        <el-button type="primary" @click="saveChanges">保存</el-button>
        <el-button @click="cancelChanges">恢复默认</el-button>
      </el-form-item>
      <el-form-item v-else class="action-buttons">
        <el-button @click="isEditing = true">编辑资料</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.user-info-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: flex-start;
  padding: 20px;
  margin-top: 20px;
  margin-left: 20px;
  height: 70vh;
}

.el-form {
  width: 100%;
  max-width: 400px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}

.el-button {
  z-index: 1;
}
</style>